﻿#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/allocators/node_allocator.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <boost/unordered_map.hpp>
#include <functional>                    //std::equal_to
#include <boost/container_hash/hash.hpp> //boost::hash
#include <boost/interprocess/offset_ptr.hpp>

using namespace boost::multi_index;

class custom_data
{
public:
    // typedef boost::interprocess::allocator<int, boost::interprocess::managed_shared_memory::segment_manager> shmem_vector_allocator;
    // typedef boost::interprocess::vector<int, shmem_vector_allocator> my_vector;

    // 创建一个分配器,内部使用的是"托管共享内存段管理器"，段管理器负责管理位于共享内存内部的内存
    typedef boost::interprocess::allocator<char, boost::interprocess::managed_shared_memory::segment_manager> shmem_string_allocator;
    // 使用新建的分配器定义string对应的数据类型基于boost::interprocess::basic_stirng，经过分配器访问段管理器
    typedef boost::interprocess::basic_string<char, std::char_traits<char>, shmem_string_allocator> shmem_string;

    struct data_body
    {
        data_body(const shmem_string_allocator &alloc)
            : data(alloc)
        {
        }
        // my_vector<shmem_string> datas;
        shmem_string data;    // 数据
        uint64_t access_time; // 上次访问时间
    };

    typedef boost::interprocess::node_allocator<std::pair<const boost::interprocess::string, data_body>, boost::interprocess::managed_shared_memory::segment_manager> shmem_data_map_allocator;
    typedef boost::interprocess::map<const boost::interprocess::string, data_body, std::less<boost::interprocess::string>, shmem_data_map_allocator> shmem_data_map;

    typedef boost::interprocess::allocator<std::pair<const uint64_t, boost::interprocess::string>, boost::interprocess::managed_shared_memory::segment_manager> shmem_access_time_map_allocator;
    typedef boost::interprocess::multimap<const uint64_t, boost::interprocess::string, std::less<uint64_t>, shmem_access_time_map_allocator> shmem_access_time_map;

    custom_data();
    void init(boost::interprocess::managed_shared_memory &segment);

    bool set(std::string key, std::string value);

private:
    boost::interprocess::managed_shared_memory segement_;
    shmem_data_map *data_map_ptr_ = nullptr;               // key:查询条件, value:查询结果
    shmem_access_time_map *access_time_map_ptr_ = nullptr; // key:上次访问时间, value:查询条件
    boost::interprocess::interprocess_mutex *mutex_ptr_ = nullptr;
};
